const { src, dest, parallel, series, watch } = require('gulp')

const del = require('del')
const browserSync = require('browser-sync')

const loadPlugins = require('gulp-load-plugins')
const plugins = loadPlugins()
const bs = browserSync.create() // 自动创建开发服务器
const data = {
  menus: [
    {
      name: 'Home',
      icon: 'aperture',
      link: 'index.html'
    },
    {
      name: 'About',
      link: 'about.html'
    }
  ],
  pkg: require('./package.json'),
  date: new Date()
}

const clean = () => {
  return del(['dist', 'temp'])
}

const style = () => { // 编译scss样式
  return src('src/assets/styles/*.scss', { base: 'src' })
    .pipe(plugins.sass({ outputStyle: 'expanded' }))
    .pipe(dest('temp')) // 放入临时目录
    .pipe(bs.reload({ stream: true }))
}

const script = () => { // 编译js
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.babel({ presets: ['@babel/preset-env'] }))
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}

const page = () => { // 编译模板页面
  return src('src/*.html', { base: 'src' })
    .pipe(plugins.swig({ data, defaults: { cache: false } })) // 防止模板缓存导致页面不能及时更新
    .pipe(dest('temp'))
    .pipe(bs.reload({ stream: true }))
}


const image = () => {
  return src('src/assets/images/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const font = () => {
  return src('src/assets/fonts/**', { base: 'src' })
    .pipe(plugins.imagemin())
    .pipe(dest('dist'))
}

const lint = () => {
  return src('src/assets/scripts/*.js', { base: 'src' })
    .pipe(plugins.eslint())
    .pipe(plugins.eslint.format()) // format（）将lint结果输出到控制台。
    // 使进程退出时具有错误代码（1）
    // lint错误，最后将流和管道返回failAfterError
    .pipe(plugins.eslint.failAfterError());
}

const extra = () => { // 额外文件挪进dist
  return src('public/**', { base: 'public' })
    .pipe(dest('dist'))
}
const serve = () => {
  // 启动本地服务
  // 监视源代码编译，自动同步到dist 
  watch('src/assets/styles/*.scss', style)
  watch('src/assets/scripts/*.js', script)
  watch('src/*.html', page)
  // watch('src/assets/images/**', image)
  // watch('src/assets/fonts/**', font)
  // watch('public/**', extra)
  watch([
    'src/assets/images/**',
    'src/assets/fonts/**',
    'public/**'
  ], bs.reload) // 监视这三种文件变化

  bs.init({
    notify: false, // 提示关闭
    port: 2080, // 端口
    open: true, // 自动打开浏览器
    files: 'dist/**', // 自动刷新
    server: {
      baseDir: ['temp', 'src', 'public'], // 构建过程请求图片
      routes: {
        '/node_modules': 'node_modules' // 特殊路由改变node_modules路径
      }
    }
  })
}
const useref = () => {  // 合并文件
  return src('temp/*.html', { base: 'temp'})
    .pipe(plugins.useref({ searchPath: ['temp', '.']})) // 创建转化流
    // 分别使用插件压缩 html js css
    .pipe(plugins.if(/\.js$/, plugins.uglify()))  // if判断是什么文件
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true, // 折叠所有空白字符
      minifyCSS: true,  // 引用合并文件的压缩
      minifyJS: true
    })))
    .pipe(dest('dist'))
}

const compile = parallel(style, script, page)

const build =  series(  // 打包上线
  clean,
  parallel(
    series(compile, useref),
    image,
    font,
    extra
  )
)

const develop = series(compile, serve)

module.exports = {
  clean,
  build,
  serve,
  lint
}